<!-- 部门列表 -->
<template>
  <div class="dept-list">
    <div class="list-item">
      <div ref="dgtools" class="filter-container">
        <el-tag size="medium" effect="dark" type="warning"><b>部门</b></el-tag>
        <div class="dgts-fm">
          <el-button type="primary" icon="el-icon-plus" @click="adupDept(1)">新增</el-button>
          <el-button type="primary" icon="el-icon-edit" @click="adupDept(2)">修改</el-button>
          <el-button type="primary" icon="el-icon-delete" @click="delDept">删除</el-button>
        </div>
      </div>

      <el-table :ref="dgDept.tbName" :data="dgDept.list" row-key="id" default-expand-all :height="bodyHeight + 30" border
        fit :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :highlight-current-row="true"
        @row-click="clickDeptRow" @select="checkDeptRow" @select-all="disableAllSel">
        <el-table-column fixed="left" type="selection" width="40" align="center"></el-table-column>

        <el-table-column label="部门名称" prop="name">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
            <span class="dept-info" v-if="scope.row.isDefault == 1">默</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="list-item">
      <div class="filter-container">
        <el-tag size="medium" effect="dark" type="success"><b>角色</b></el-tag>
        <div class="dgts-fm">
          <el-button type="primary" icon="el-icon-plus" @click="adupRole(1)">新增</el-button>
          <el-button type="primary" icon="el-icon-edit" @click="adupRole(2)">修改</el-button>
          <el-button type="primary" icon="el-icon-delete" @click="delRole">删除</el-button>
          <el-button type="primary" icon="el-icon-setting" @click="authSet(1)">权限设置</el-button>
        </div>
      </div>

      <el-table :ref="dgRole.tbName" :data="dgRole.list" row-key="id" default-expand-all :height="bodyHeight + 30" border
        fit :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :highlight-current-row="true"
        @row-click="clickRoleRow" @select="checkRoleRow" @select-all="disableAllSel">
        <el-table-column fixed="left" type="selection" width="40" align="center"></el-table-column>

        <el-table-column label="角色名称" prop="name" width="140">
          <template slot-scope="{row}">
            <span>{{ row.name }}</span>
            <span class="dept-info" v-if="row.isDefault == 1">默</span>
          </template>
        </el-table-column>
        <el-table-column label="描述" prop="description"></el-table-column>
        <el-table-column label="状态" prop="status" width="60" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 'NORMAL'" class="c-green">正常</span>
            <span v-else-if="scope.row.status == 'LOCKED'" class="c-red">已锁定</span>
            <span v-else class="c-gray">已删除</span>
          </template>
        </el-table-column>

        <!-- <el-table-column label="系统默认" prop="isDefault" align="center" width="70" :resizable="false">
          <template slot-scope="scopes">
            <span v-if="scopes.row.isDefault == 1" class="c-red">是</span>
            <span v-else class="c-gray">否</span>
          </template>
        </el-table-column> -->

        <!-- <el-table-column label="添加时间" prop="atime" width="140"></el-table-column> -->
      </el-table>
    </div>

    <div class="list-item">
      <div class="filter-container">
        <el-tag size="medium" effect="dark" type="danger"><b>员工</b></el-tag>
        <div class="dgts-fm">
          <el-input style="width: 130px" placeholder="员工姓名/手机号" maxlength="11" v-model="dgStaff.ps.find"></el-input>

          <el-button type="primary" icon="el-icon-search" @click="getStaffDgList()">搜索</el-button>
          <el-button type="primary" icon="el-icon-setting" @click="authSet(2)">权限设置</el-button>
        </div>
      </div>

      <el-table :ref="dgStaff.tbName" :data="dgStaff.list" border fit :height="bodyHeight + 30"
        :highlight-current-row="true" @row-click="clickSingleRow" @select="checkSingleRow" @select-all="disableAllSel">
        <el-table-column fixed="left" type="selection" width="40" align="center"></el-table-column>

        <el-table-column label="员工姓名/手机号" prop="realName">
          <template slot-scope="scopes">
            <b>{{ scopes.row.realName }}</b> / {{ scopes.row.phone }}
          </template>
        </el-table-column>

        <el-table-column label="部门/角色" prop="deptName" width="110">
          <template slot-scope="scopes">
            <b>{{ scopes.row.deptName }}</b> / {{ scopes.row.roleName }}
          </template>
        </el-table-column>

        <el-table-column label="添加时间" prop="addTime" width="140"></el-table-column>
      </el-table>
    </div>

    <AdupDept v-if="adupDeptMd.state" :myData="adupDeptMd" @myClick="setAdupDeptMd" @reloadDg="getDeptDgList" />

    <AdupRole v-if="adupRoleMd.state" :myData="adupRoleMd" @myClick="setAdupRoleMd" @reloadDg="getDeptRoleDgList" />

    <SetAuthMenu v-if="setAuthMenuMd.state" :myData="setAuthMenuMd" @myClick="setSetAuthMenuMd" />

  </div>
</template>

<script>
import DataGridBase from '@/views/mixins/DataGridBase';
import DataGridResize from '@/views/mixins/DataGridResize';
import elDragDialog from '@/directive/el-drag-dialog';

import AdupDept from './adup-dept';
import AdupRole from './adup-role';
import SetAuthMenu from './set-auth-menu';

import * as authManageService from '@/api/services/auth.manage.service';

export default {
  name: 'DeptRoleList',
  mixins: [DataGridBase, DataGridResize],
  directives: { elDragDialog },
  components: { AdupDept, AdupRole, SetAuthMenu },
  data() {
    return {
      // 添加/修改部门-弹框
      adupDeptMd: { state: false },
      dgDept: { // 部门列表数据
        tbName: 'deptListTb',
        list: [],
        selRows: [],
        ps: {
          page: 1, rows: 20,
        },
      },

      // 当前tab选中key
      activeName: 'tab1',
      // 添加/修改角色-弹框
      adupRoleMd: { state: false },
      dgRole: { // 角色列表数据
        tbName: 'roleListTb',
        list: [],
        selRows: [],
        deptId: '', // 所属部门id
        ps: {
          page: 1, rows: 20,
        },
      },

      dgStaff: { // 员工列表数据
        tbName: 'staffListTb',
        list: [],
        selRows: [],
        roleId: '', // 所属角色id
        ps: {
          page: 1, rows: 1000,
          // 员工姓名/手机号关键字
          find: ''
        },
      },

      // 设置功能菜单-弹框
      setAuthMenuMd: { state: false },

    }
  },
  created() {
    const that = this;

    that.getDeptDgList();
    that.getStaffDgList();
  },
  methods: {
    // changeTab(e){
    //   const that = this;
    //   // console.log('点击了tab', e);
    //   // 重新渲染，因为dom渲染在请求数据之前
    //   that.$nextTick(() => {
    //     if(e.index == 0){
    //       that.$refs[that.dgRole.tbName].doLayout();
    //     }else if(e.index == 1){
    //       that.$refs[that.dgStaff.tbName].doLayout();
    //     }
    //   });
    // },
    /**
     * 添加/修改-部门
     * @param type 操作类型 1-添加 2-修改
     */
    adupDept(type) {
      let that = this, rows = that.dgDept.selRows;

      let e = { state: true };
      if (type == 1) {// 添加
        if (rows.length == 1) {
          e.pobj = rows[0];
        }

        that.setAdupDeptMd(e);
      } else if (type == 2) {// 修改
        if (rows.length != 1) {
          that.U.qerror('请选择一条数据');
        } else {
          e.obj = rows[0];

          that.setAdupDeptMd(e);
        }
      }
    },
    /**
     * 打开/关闭-添加/修改部门-弹框
     * @param e 传入的数据
     */
    setAdupDeptMd(e) {
      const that = this;

      if (e.state) {// 打开
        that.adupDeptMd = e;
      } else {// 关闭
        that.adupDeptMd = e;
      }
    },
    /** 删除-部门 */
    delDept() {
      const that = this, U = that.U, rows = that.dgDept.selRows;

      if (rows.length != 1) {
        U.qerror('请选择一条数据');
      } else {
        let row = rows[0];

        U.qconfim(`确定删除部门【${row.name}】？`).then(r => {
          if (r) {
            let loading = U.qloading('删除中...');

            authManageService.delDept({ did: row.id }).then(res => {
              U.qclose(loading);

              if (!res || res.code != 1) {
                U.qerror(res.msg);
              } else {
                U.qsuccess(res.msg);

                // 调用方法-重新加载
                that.getDeptDgList();
                // 清空
                that.dgDept.selRows = [];
              }
            });
          }
        });
      }
    },
    /** 获取-部门列表数据 */
    getDeptDgList() {
      const that = this, ps = that.dgDept.ps;

      let loading = that.U.qloading('数据请求中...');
      authManageService.getDeptList(ps).then(res => {
        that.U.qclose(loading);

        if (!res || res.code != 1) {
          that.U.qerror('数据请求失败');
        } else {
          let list = res.data;
          list.forEach(it => { it.dgName = 'dgDept'; });
          that.dgDept.list = that.U.line2treeData(list, 'pid');
        }
      }).catch(() => { that.U.qclose(loading); });
    },
    /**
     * 点击-部门列表行复选框
     */
    checkDeptRow(selection, row) {
      const that = this;

      that.checkSingleRow(selection, row);

      // 选中了一行，且不是同一行，才查询
      if (that.dgDept.selRows.length == 1) {
        that.dgRole.deptId = row.id;
        that.getDeptRoleDgList(row.id);
        // 查询指定部门的所有员工
        that.getStaffDgList({ deptIds: row.id });
      } else {
        // 清空角色列表
        that.dgRole.list = [];
        that.dgRole.deptId = '';
      }
    },
    /**
     * 点击-部门列表行
     */
    clickDeptRow(row, column, event) {
      const that = this;

      that.clickSingleRow(row, column, event);

      // 选中了一行，且不是同一行，才查询
      if (that.dgDept.selRows.length == 1) {
        that.dgRole.deptId = row.id;
        that.getDeptRoleDgList(row.id);
        // 查询指定部门的所有员工
        that.getStaffDgList({ deptIds: row.id });
      } else {
        // 清空角色列表
        that.dgRole.list = [];
        that.dgRole.deptId = '';
      }
    },
    /**
     * 添加/修改-角色
     * @param type 操作类型 1-添加 2-修改
     */
    adupRole(type) {
      let that = this, rows = that.dgRole.selRows;

      if (!that.dgRole.deptId) {
        that.U.qerror('请先选择一条部门数据');
      } else {
        let e = { state: true };
        if (type == 1) {// 添加
          if (rows.length == 1) {
            e.pobj = rows[0];
          }

          e.deptId = that.dgRole.deptId;
          that.setAdupRoleMd(e);
        } else if (type == 2) {// 修改
          if (rows.length != 1) {
            that.U.qerror('请选择一条数据');
          } else {
            e.obj = rows[0];

            that.setAdupRoleMd(e);
          }
        }
      }
    },
    /**
     * 点击-角色列表行复选框
     */
    checkRoleRow(selection, row) {
      const that = this;

      console.log('点击复选框进来了吗？');
      that.checkSingleRow(selection, row);

      // 选中了一行，且不是同一行，才查询
      if (that.dgRole.selRows.length == 1) {
        that.dgStaff.roleId = row.id;
        that.getStaffDgList({ roleIds: row.id });
      } else {
        // 清空员工列表
        that.dgStaff.roleId = '';
        that.getStaffDgList({ deptIds: that.dgRole.deptId });
      }
    },
    /**
     * 点击-角色列表行
     */
    clickRoleRow(row, column, event) {
      const that = this;
      console.log('点击行进来了吗？');
      that.clickSingleRow(row, column, event);

      // 选中了一行，且不是同一行，才查询
      if (that.dgRole.selRows.length == 1) {
        that.dgStaff.roleId = row.id;
        that.getStaffDgList({ roleIds: row.id });
      } else {
        // 清空员工列表
        that.dgStaff.roleId = '';
        that.getStaffDgList({ deptIds: that.dgRole.deptId });
      }
    },
    /**
     * 打开/关闭-添加/修改角色-弹框
     * @param e 传入的数据
     */
    setAdupRoleMd(e) {
      const that = this;

      if (e.state) {// 打开
        that.adupRoleMd = e;
      } else {// 关闭
        that.adupRoleMd = e;
      }
    },
    /** 删除-角色 */
    delRole() {
      const that = this, U = that.U, rows = that.dgRole.selRows;

      if (rows.length != 1) {
        U.qerror('请选择一条数据');
      } else {
        let row = rows[0];

        U.qconfim(`确定删除角色【${row.name}】？`).then(r => {
          if (r) {
            let loading = U.qloading('删除中...');

            authManageService.delDeptRole({ did: row.id }).then(res => {
              U.qclose(loading);

              if (!res || res.code != 1) {
                U.qerror(res.msg);
              } else {
                U.qsuccess(res.msg);

                // 调用方法-重新加载
                that.getDeptRoleDgList(that.dgRole.deptId);

                // 清空
                that.dgRole.selRows = [];
              }
            });
          }
        });
      }
    },
    /** 获取-指定部门对应角色列表数据 */
    getDeptRoleDgList(deptId) {
      let that = this, ps = that.U.scopy(that.dgRole.ps);
      ps.deptId = deptId;

      let loading = that.U.qloading('数据请求中...');
      authManageService.getDeptRoleList(ps).then(res => {
        that.U.qclose(loading);

        if (!res || res.code != 1) {
          that.U.qerror('数据请求失败');
        } else {
          let list = res.data;
          list.forEach(it => { it.dgName = 'dgRole'; });
          that.dgRole.list = that.U.line2treeData(list, 'pid');
        }
      }).catch(() => { that.U.qclose(loading); });
    },


    /** 获取-员工列表数据 */
    getStaffDgList(p) {
      let that = this, ps = that.U.scopy(that.dgStaff.ps);
      ps = { ...ps, ...p };

      let loading = that.U.qloading('数据请求中...');
      authManageService.getStaffList(ps).then(res => {
        that.U.qclose(loading);

        if (!res || res.code != 1) {
          that.U.qerror('数据请求失败');
        } else {
          let list = res.data;

          let reslist = [];
          list.forEach(it => {
            reslist.push({
              dgName: 'dgStaff', // table数据对象名称
              id: it.id,
              bid: it.baseUserId.id, // 用户基类id
              realName: it.baseUserId.realName,
              phone: it.baseUserId.phone,
              deptId: it.deptId.id,
              deptName: it.deptId.name,
              roleId: it.roleId.id,
              roleName: it.roleId.name,
              addTime: it.addTime
            });
          });

          that.dgStaff.list = reslist;
        }
      }).catch(() => { that.U.qclose(loading); });
    },


    // 打开/关闭-设置权限菜单-弹框
    setSetAuthMenuMd(e) {
      const that = this;

      that.setAuthMenuMd = e;
    },
    /**
     * 设置-功能权限
     * @param type 设置类型 1-角色功能权限 2-用户功能权限
     */
    authSet(type) {
      const that = this, U = that.U, md = that.setAuthMenuMd;

      if (type == 1) {
        let rows = that.dgRole.selRows;

        if (rows.length != 1) {
          U.qerror('请选择一条数据');
        } else {
          that.setSetAuthMenuMd({ state: true, role: rows[0] });
        }
      } else if (type == 2) {
        let rows = that.dgStaff.selRows;

        if (rows.length != 1) {
          U.qerror('请选择一条数据');
        } else {
          that.setSetAuthMenuMd({ state: true, user: rows[0] });
        }
      }
    },



  }
}
</script>

<style lang="less" scoped>
.dept-list ::v-deep {
  display: flex;

  .list-item:not(:last-child) {
    margin-right: 10px;
  }

  .list-item:nth-of-type(1) {
    width: 300px;
  }

  .list-item:nth-of-type(2) {
    width: 470px;
  }

  .list-item:nth-of-type(3) {
    flex: 1;
  }

  .list-title {
    font-size: 18px;
    color: #fff;
    font-family: 'Courier New', Courier, monospace;
    border: 1px solid #ff6300;
    border-radius: 5px;
    background: #ff6300;
  }

  .dept-info {
    position: absolute;
    bottom: calc((100% - 17px)/2);
    right: 0px;
    font-size: 12px;
    border: 1px solid #ff7300;
    border-radius: 3px;
    padding: 0px 2px;
    color: #ff6300;
    margin-right: 10px;
  }
}
</style>
